package dxunderground.winampController.Server;

import java.io.IOException;
import java.net.ServerSocket;

import javax.swing.DefaultListModel;

import dxunderground.winampController.Common.GUI;
import dxunderground.winampController.Server.GUI.ButtonActions;

public class Server implements Runnable {
	private int port = 4444;
	private boolean listening = true;
	private GUI gui;
	private ButtonActions buttonActions;
	private DefaultListModel listModel;

	public Server(ButtonActions buttonActions, GUI gui, DefaultListModel listModel) {
		this.gui = gui;
		this.buttonActions = buttonActions;
		this.listModel = listModel;
	}

	public void setListening(boolean listening) {
		this.listening = listening;
	}

	public void run() {
		ServerSocket serverSocket = null;

		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			System.err.println("Could not listen on port: " + port);
			System.exit(-1);
		}

		System.out.println("Searching for clients.");

		while (listening) {
			try {
				new Thread(new ServerThread(serverSocket.accept(), this.gui, this.buttonActions, this.listModel)).start();
			} catch (IOException e) {
				System.err.println(e);
			}
		}
		try {
			serverSocket.close();
		} catch (IOException e) {
			System.err.println(e);
		}

		System.out.println("Server stopped.");
	}
}